import React from 'react';
import Taro from '@tarojs/taro';

import {connect} from 'react-redux';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';
import {View, Image} from '@tarojs/components';
import {
  OSS_PATH_PREFIX,
  OSS_BASE_PATH_PREFIX,
  IMAGE_EMPTY,
  GAME_SHARE_TITLE,
  SYNTHETCI_SEELCT_IP_STORE,
} from './constant';
import {AtBadge} from 'taro-ui';
import PageLoading from '../../common/PageLoading';

import './index.less';
import 'taro-ui/dist/style/components/flex.scss';
import 'taro-ui/dist/style/components/badge.scss';

actions().actions.loadReducer();

// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class SyntheticCardLibraryPa extends React.Component<Partial<T.IProps>, any> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      query: {},
      pics: {
        loadingIcon: OSS_BASE_PATH_PREFIX + '/gameLoadingWhite.png',
        emptyIcon: OSS_BASE_PATH_PREFIX + '/empty.png',
        gameShareIcon: OSS_BASE_PATH_PREFIX + '/gameShareIcon.png', // 分享至朋友圈
        gameShareThum: OSS_BASE_PATH_PREFIX + '/gameShareThum.png', // 分享缩略图
      },
      empty: {
        text: 'IP系列添加中,敬请期待...',
      },
      listText: 'IP系列添加中,敬请期待...',
      // 角标配置
      badge: {
        max: 100000,
      },
      imageError: {},
    };
  }

  componentDidShow() {
    this.handleGetRouterParams(); // 获取路由参数
    this.props.actions.init();
  }

  componentWillReceiveProps(nextProps: Readonly<Partial<T.IProps>>, nextContext: any): void {
    if (nextProps.main.status.loadingIp == false && this.props.main.status.loadingIp == true) {
      const {query} = this.state;
      // 按第一个ip去查询相关卡片信息
      let ipItem = [];
      let currentTab = -1;
      if (nextProps.main.ipItems.length > 0) {
        // 如果有传参 ipid
        if (query.ipId) {
          let currentIpIndex = nextProps.main.ipItems.findIndex((i) => i.ipId == query.ipId);
          if (currentIpIndex > -1) {
            currentTab = currentIpIndex;
            ipItem = nextProps.main.ipItems[currentTab];
          } else {
            ipItem = nextProps.main.ipItems[0];
            currentTab = 0;
          }
        } else {
          ipItem = nextProps.main.ipItems[0];
          currentTab = 0;
        }
      }
      console.log('index.tsx currentTab', currentTab);
      this.handleQueryCards(ipItem);
      this.setState({
        currentTab,
      });
    }
  }

  /**
   * 获取路由参数
   */
  handleGetRouterParams = () => {
    let params = Taro.getCurrentInstance()?.router?.params;
    console.log('index.tsx handleGetRouterParams', params);

    // 收藏进来的就直接去首页
    if (params.favorite) {
      Taro.redirectTo({
        url: '/pages/package-I/home/index',
      });
      return;
    }
    this.handleQuery();

    this.setState({
      query: params,
    });
  };

  /**
   * 查询列表
   */
  handleQuery = () => {
    this.handleQueryIps();
  };

  /**
   *查询ip列表
   */
  handleQueryIps = () => {
    let params = {};
    this.props.actions.action.loadIpItems(params);
  };

  /**
   *查询卡片列表
   */
  handleQueryCards = (data) => {
    console.log('index.tsx handleQueryCards data', data);

    let params = {
      ipId: data.ipId,
    };
    this.props.actions.action.loadCardItems(params);
  };

  componentWillUnmount() {
    this.props.actions.clean();
  }

  render() {
    if (!this.props.main) return null;
    let {
      main: {
        isLoading,
        status: {loadingIp, loadingCard},
        ipItems,
        cardItems,
      },
    } = this.props;
    console.log(isLoading);

    return (
      <View className="pageSyntheticCardLibraryPa">
        {loadingIp ? (
          <></>
        ) : (
          <>
            {ipItems.length > 0 ? this.renderTabs(ipItems) : this.renderEmptyContent()}
            {ipItems.length > 0 ? this.renderTabsContent(cardItems) : <></>}
          </>
        )}
      </View>
    );
  }

  /**
   * 渲染加载内容
   * @returns
   */
  renderLoadingContent(status) {
    return status ? (
      <View className="loadingContent">
        <PageLoading />
      </View>
    ) : (
      <></>
    );
  }

  /**
   * 渲染空
   */
  renderEmptyContent() {
    const {
      pics: {emptyIcon},
      empty: {text},
    } = this.state;

    return (
      <View className="emptyContent">
        <Image src={emptyIcon} className="emptyIcon" />
        <View className="emptyExtraTitle">{text}</View>
      </View>
    );
  }

  /**
   * 渲染tab切换
   */
  renderTabs(items) {
    console.log('syntheticCardLibray renderTabs items', items);
    const {currentTab} = this.state;

    console.log('renderTab currentTab', currentTab);

    return (
      <View className="TabRow">
        {items.map((i: any, index: number) => (
          <View
            className="tabCol"
            key={'tab' + index}
            onClick={() => this.handleTabIpChange(index)}
            style={{
              backgroundColor: index == currentTab ? '#fff' : '#856DAE',
              zIndex: currentTab == index ? 1 : 0,
              width: `calc((100% + 45px) / ${items.length})`,
            }}
          >
            <View className="tabTitle" style={{color: index == currentTab ? '#2F0774' : '#fff'}}>
              {i.ipName}
            </View>
          </View>
        ))}
      </View>
    );
  }

  /**
   * 切换tab ip类型
   */
  handleTabIpChange = (e) => {
    const {
      main: {ipItems},
    } = this.props;
    this.setState({
      currentTab: e,
    });

    let currentIp = ipItems.find((i, index) => index == e);
    console.log('index.tsx handleTabIpChange ipItems currentIp', currentIp);
    if (currentIp && currentIp.ipId) {
      Taro.setStorageSync(SYNTHETCI_SEELCT_IP_STORE, {...currentIp}); // 存入缓存
      this.handleQueryCards(currentIp);
    }
  };

  /**
   * 渲染tab内容
   * @returns
   */
  renderTabsContent(items) {
    console.log('syntheticCardLibray renderTabsContent items', items);
    const {
      main: {
        status: {loadingCard},
      },
    } = this.props;
    return loadingCard ? <></> : this.renderListContent(items);
  }

  /**
   * 渲染空列表信息
   */
  renderEmptyCardContent() {
    const {
      listText,
      pics: {emptyIcon},
    } = this.state;

    return (
      <View className="CardEmptyContent">
        <Image src={emptyIcon} className="emptyIcon" />
        <View className="emptyExtraTitle">{listText}</View>
      </View>
    );
  }

  /**
   * 渲染列表
   */
  renderListContent(items) {
    const {badge} = this.state;
    return (
      <View className="listContent">
        {items.length > 0 ? (
          <View className="at-row cards">
            {items.map((i: any, index: number) => (
              <View key={'list' + index} className="at-col at-col-4 cardItem">
                {i.cardNum > 0 ? (
                  <AtBadge value={i.cardNum} maxValue={badge.max}>
                    <View className="cThumInfo">
                      <Image
                        src={i.imgUrl || IMAGE_EMPTY}
                        className="cardImage"
                        mode="scaleToFill"
                        onError={(e) =>
                          this.handleImageError(e, index, {
                            propName: 'cardItems',
                            imageState: 'imgUrl',
                          })
                        }
                      />
                      <View className="cExtraLabel">已获得</View>
                    </View>
                  </AtBadge>
                ) : (
                  <View className="cThumInfo">
                    <Image
                      style={{backgroundColor: '#000', opacity: 0.2, borderRadius: 10}}
                      src={i.imgUrl || IMAGE_EMPTY}
                      className="cardImage"
                      mode="scaleToFill"
                      onError={(e) =>
                        this.handleImageError(e, index, {
                          propName: 'cardItems',
                          imageState: 'imgUrl',
                        })
                      }
                    />
                    <View className="cExtraLabel">未获得</View>
                  </View>
                )}
              </View>
            ))}
          </View>
        ) : (
          this.renderEmptyCardContent()
        )}
      </View>
    );
  }

  /**
   * 图片加载错误
   * @param e
   * @param index
   */
  handleImageError = (e, index, item) => {
    const {main} = this.props;
    const {propName, imageState} = item;
    let {imageError} = this.state;
    if (imageError[propName]) {
      imageError[propName] = imageError[propName].concat([index]);
    } else {
      imageError[propName] = [index];
    }
    let result = JSON.parse(JSON.stringify(main[propName]));
    let currentImage = imageError[propName];
    let ids = currentImage;
    ids.map((i) => {
      result[i] = {
        ...result[i],
        [imageState]: IMAGE_EMPTY,
      };
    });
    this.props.actions.action.commonChange('main.' + propName, result);
  };

  /**
   * 收藏
   * @param res
   * @returns
   */
  onAddToFavorites(res) {
    const {
      pics: {gameShareIcon},
    } = this.state;

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      query: 'favorite=true',
    };
  }
}
